package cn.tedu.apiday10;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

//测试网络编程的服务器端
//服务器的职责：接收客户端发来的数据和给客户端发出数据
public class Server {
    public static void main(String[] args) throws IOException {
        //启动服务器，等待客户端的连接请求
        //参数是端口号，0到65536，其中0到1024被系统占用
        ServerSocket serverSocket = new ServerSocket(8000);
        System.out.println("服务器已启动");
        //服务器接收客户端发来的请求并建立通信通道
        Socket socket = serverSocket.accept();
        System.out.println("来了一个请求");
        //接收客户端发来的数据======in
        InputStream inputStream = socket.getInputStream();
        //读取数据
        for (int i = 0; i < 5; i++) {
            //把读取到的数据，从int类型强转成char类型
            char b = (char) inputStream.read();
            System.out.print(b);
        }
        //给客户端发送数据
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("world".getBytes());
        outputStream.flush();
    }
}
